package com.mls.guardian.executor.master;

import com.mls.guardian.common.RemoteUtil;
import com.mls.guardian.container.MasterContainer;
import com.mls.guardian.dataobj.ServerUpgradeInfo;
import com.mls.guardian.protocol.RemoteBody;
import com.mls.guardian.protocol.RemoteCommand;
import com.mls.guardian.protocol.body.AppRestartBody;
import com.mls.guardian.protocol.body.ServerUpgradeInfoBody;
import com.mls.guardian.remoting.executor.RemoteExecutor;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * Created by root on 15-12-11.
 */
public class GetUpgradeVersionExcutor implements RemoteExecutor {
    private static final Logger log = LoggerFactory.getLogger(GetUpgradeVersionExcutor.class);
    private MasterContainer container;

    public GetUpgradeVersionExcutor(MasterContainer container) {
        this.container = container;
    }

    @Override
    public RemoteBody execute(ChannelHandlerContext ctx, RemoteCommand request) throws Exception {
        List<Future<RemoteBody>> futures = new ArrayList<>();

        ServerUpgradeInfoBody responseBody = new ServerUpgradeInfoBody();
        List<ServerUpgradeInfo> responseList = new ArrayList<ServerUpgradeInfo>();

        ServerUpgradeInfoBody requestBody = (ServerUpgradeInfoBody) request.getRemoteBody();
        List<String> clientAddrs = new ArrayList<String>();
        for (ServerUpgradeInfo serverUpgradeInfo : requestBody.getUpgradeInfoList()) {
            if (serverUpgradeInfo.getIp().equals(RemoteUtil.getLocalHostIP())) {
                //MASTER
                log.info("----MASTER开始GetUpgrade----");
                String version = container.getAppController().getUpgradeVersion();
                log.info("----MASTER结束GetUpgrade----" + version);
                serverUpgradeInfo.setVersion(version);

                responseList.add(serverUpgradeInfo);
            } else {
                clientAddrs.add(serverUpgradeInfo.getIp());
            }
        }

        log.info("----Slave开始GetUpgrade----" + clientAddrs.toString());
        List<RemoteBody> remoteBodyList = container.getClientDispatch().sendRequestToClients(request, clientAddrs, -1);
        for (int i = 0; i < remoteBodyList.size(); i++) {
            ServerUpgradeInfoBody body = (ServerUpgradeInfoBody) remoteBodyList.get(i);

            if (!body.isSuc()) {
                responseBody.setSuc(false);
                responseBody.setErrorContent(body.getErrorContent());
                return responseBody;
            }

            responseList.add(body.getUpgradeInfoList().get(0));
        }
        log.info("----Slave结束GetUpgrade----");

        responseBody.setUpgradeInfoList(responseList);
        responseBody.setSuc(true);
        return responseBody;
    }
}
